#include "ad_sell.h"
#include "ui_ad_sell.h"
#include "admin_0.h"
#include "guoshu.h"
#include "value.h"
#include "dlcw.h"
#include "ad_sechname.h"
#include "hycz.h"
#include <QMessageBox>
#include <QStandardItem>
#include <QDateTime>

int buyer=0;//0为散户  1为会员
struct good *tmp;//当前商品
int num=0;
double sum=0;
int flag=0;
double disct=1.00;//折扣力度


ad_sell::ad_sell(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ad_sell)
{
    ui->setupUi(this);
    setWindowTitle("售货系统");
    tmp=p;
    ui->buyername->setText("散户(非会员)");
    ui->warning->setStyleSheet("color:rgb(255,0,0)");
    QStringList headlist;
    headlist<<"产品编号"<<"商品名"<<"购买数量"<<"购买者";
    themodel=new QStandardItemModel(50,4,this);
    themodel->setHorizontalHeaderLabels(headlist);
    ui->tableView->setModel(themodel);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->tableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->tableView->horizontalHeader()->setMinimumSectionSize(100);
    ui->tableView->verticalHeader()->setMinimumSectionSize(100);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
}

ad_sell::~ad_sell()
{
    delete ui;
}

void ad_sell::on_action_triggered()//查找商品
{
    std::string num0;
    num0=ui->goodnum->text().trimmed().toStdString();
    tmp=p;
    for(int i=0;i<count1;i++){
        if(strcmp(tmp->number,num0.c_str())==0){
            std::string tt="(盒装)";
            if(tmp->typ==1) tt="(散装)";
            ui->goodname->setText(QString::asprintf("%s%s",tmp->name,tt.c_str()));
            flag=1;
            break;
        }
        tmp=tmp->next;
    }
    if(flag==0){
        QMessageBox::information(this," ","产品未找到");
    }
}

void ad_sell::on_nextbtn_clicked()//下一个商品
{
    if(ui->sellcnt->value()<0.01) {
        QMessageBox::warning(this,"err","售卖数量不能为空");
        return;
    }
    std::string num0;
    num0=ui->goodnum->text().trimmed().toStdString();
    tmp=p;
    struct good *p1;
    p1=p;
    for(int i=0;i<count1;i++){
        if(strcmp(tmp->number,num0.c_str())==0){
            std::string tt="(盒装)";
            if(tmp->typ==1) tt="(散装)";
            ui->goodname->setText(QString::asprintf("%s%s",tmp->name,tt.c_str()));
            flag=1;
            break;
        }
        p1=tmp;
        tmp=tmp->next;
    }
    if(flag==0){
        QMessageBox::information(this," ","产品未找到");
        return;
    }
    if(tmp->typ==0){
        if(abs(ui->sellcnt->value()-(int)(ui->sellcnt->value()))>0.01) {
            QMessageBox::warning(this,"err","该商品为盒装，必须输入整数");
            return;
        }
    }
    if(buyer==1) {
        double suuum=Find_sum(_name.c_str());
        if(suuum>=300 && suuum<500)
        {
            disct = 0.95;
        }
        else if(suuum>=500&&suuum<1000)
        {
            disct = 0.9;
        }
        else if(suuum>=1000)
        {
            disct = 0.8;
        }
        if(suuum < tmp->outprice*ui->sellcnt->value()*disct){
            QMessageBox::warning(this,"余额不足","此会员余额不足，请充值");
            return;
        }
    }
    if(tmp->count < ui->sellcnt->value()){
        QMessageBox::warning(this,"err","该编号对应的商品存货不足,请检查是否输入错误");
        return;
    }
    else{
        tmp->count=(tmp->count)-(ui->sellcnt->value());
    }
    ruzhang(buyer);//入账

    //输出到表格
    //产品编号
    QStandardItem *aItem;
    aItem=new QStandardItem(QString::asprintf("%s",tmp->number));
    aItem->setTextAlignment(Qt::AlignHCenter);
    themodel->setItem(num,0,aItem);
    //产品形式
    aItem=new QStandardItem(QString::asprintf("%s",tmp->name));
    aItem->setTextAlignment(Qt::AlignHCenter);
    themodel->setItem(num,1,aItem);
    //购买数量
    aItem=new QStandardItem(QString::asprintf("%.2lf",ui->sellcnt->value()));
    aItem->setTextAlignment(Qt::AlignHCenter);
    themodel->setItem(num,2,aItem);
    //购买者
    if(buyer==1){
        aItem=new QStandardItem(QString::asprintf("%s",_name.c_str()));
    }
    else{
        aItem=new QStandardItem(QString::asprintf("散户"));
    }
    aItem->setTextAlignment(Qt::AlignHCenter);
    themodel->setItem(num,3,aItem);

    num++;
    flag=0;
    sum=sum+(ui->sellcnt->value())*(tmp->outprice)*disct;
    count01=ui->sellcnt->value();
    //当前剩余链表
    if(tmp==p){
        if(tmp->count<0.01){
            strcpy(name1,tmp->name);
            strcpy(nickname1,tmp->nickname);
            strcpy(number1,tmp->number);
            inprice1=tmp->inprice;
            outprice1=tmp->outprice;
            strcpy(indate1,tmp->indate);
            strcpy(purchasedate1,tmp->purchasedate);
            exp1=tmp->exp;
            typ1=tmp->typ;
            p=tmp->next;
            count1-=1;
        }
        else{
            strcpy(name1,tmp->name);
            strcpy(nickname1,tmp->nickname);
            strcpy(number1,tmp->number);
            inprice1=tmp->inprice;
            outprice1=tmp->outprice;
            strcpy(indate1,tmp->indate);
            exp1=tmp->exp;
            strcpy(purchasedate1,tmp->purchasedate);
            typ1=tmp->typ;
        }
    }
    else{
        if(tmp->count<0.01){
            strcpy(name1,tmp->name);
            strcpy(nickname1,tmp->nickname);
            strcpy(number1,tmp->number);
            inprice1=tmp->inprice;
            outprice1=tmp->outprice;
            strcpy(indate1,tmp->indate);
            exp1=tmp->exp;
            strcpy(purchasedate1,tmp->purchasedate);
            typ1=tmp->typ;
            p1->next=tmp->next;
            count1-=1;
        }
        else{
            strcpy(name1,tmp->name);
            strcpy(nickname1,tmp->nickname);
            strcpy(number1,tmp->number);
            inprice1=tmp->inprice;
            outprice1=tmp->outprice;
            strcpy(indate1,tmp->indate);
            strcpy(purchasedate1,tmp->purchasedate);
            typ1=tmp->typ;
            exp1=tmp->exp;
        }
    }
    //写入文件
    FILE *w=fopen("shiyan4.txt","w");
    if(w==NULL){
        QMessageBox::warning(this,"err","文件打开失败");
        return;
    }
    int nx=count1;
    struct good *pp;
    pp=p;
    fwrite(&nx,sizeof(int),1,w);
    for(int i=0;i<count1;i++){
        fwrite(pp,sizeof(struct good),1,w);
        pp=pp->next;
    }
    fclose(w);
    //历史卖出链表
    QDateTime tp=QDateTime::currentDateTime();
    //char purdate[30];
    if(ss2!=NULL){
        struct good *shaobing;
        shaobing=ss2;
        for(int i=1;i<count3;i++){
            shaobing=shaobing->next;
        }
        struct good *p1;
        p1=(struct good*)malloc(sizeof(struct good));
        shaobing->next=p1;
        p1->next=NULL;
        strcpy(p1->name,name1);
        strcpy(p1->nickname,nickname1);
        strcpy(p1->number,number1);
        p1->count=count01;
        p1->inprice=(ui->sellcnt->value())*((tmp->outprice)*disct-tmp->inprice);
        p1->outprice=outprice1;
        strcpy(p1->indate,indate1);
        p1->typ=typ1;
        strcpy(p1->purchasedate,tp.toString("yy-MM-dd hh:mm:ss").toStdString().c_str());
        p1->exp=exp1;
        count3+=1;
    }
    else{
        struct good *shaobing;
        shaobing=(struct good*)malloc(sizeof(struct good));
        ss2=(struct good*)malloc(sizeof(struct good));
        ss2->next=shaobing;
        strcpy(shaobing->name,name1);
        strcpy(shaobing->nickname,nickname1);
        strcpy(shaobing->number,number1);
        shaobing->count=count01;
        shaobing->inprice=(ui->sellcnt->value())*((tmp->outprice)*disct-tmp->inprice);
        shaobing->outprice=outprice1;
        strcpy(shaobing->indate,indate1);
        shaobing->typ=typ1;
        strcpy(shaobing->purchasedate,tp.toString("yy-MM-dd hh:mm:ss").toStdString().c_str());
        shaobing->exp=exp1;
        count3+=1;
        ss2=ss2->next;
        ss2->next=NULL;
    }
    FILE *w1=fopen("shiyan6.txt","w");
    if(w1==NULL){
        QMessageBox::warning(this,"err","文件打开失败");
        return;
    }
    nx=count3;
    pp=ss2;
    fwrite(&nx,sizeof(int),1,w1);
    for(int i=0;i<count3;i++){
        fwrite(pp,sizeof(struct good),1,w1);
        pp=pp->next;
    }
    fclose(w1);
    //输入组件初始化
    ui->goodnum->clear();
    ui->sellcnt->setValue(0.00);
    ui->goodname->setText("xxxxxxxxxxxx");
}

void ad_sell::on_action_2_triggered()//返回主菜单
{
    Admin_0 *a=new Admin_0(this);
    this->close();
    a->show();
}

void ad_sell::on_pushButton_2_clicked()//会员买账
{
    ad_sechname *cz=new ad_sechname(this);
    cz->show();
    if(cz->exec()==QDialog::Accepted){
        ui->buyername->setText(QString::asprintf("%s",_name.c_str()));
        buyer=1;
    }
    else{
        ui->buyername->setText("散户(非会员)");
        buyer=0;
    }
}

void ad_sell::ruzhang(int x)//x=0散户   x=1会员
{
    double sum0=-1;//会员剩余金额
    if(x==1){
        sum0=Find_sum(_name.c_str());//查询会员等级并调整折扣力度
        if(sum0>=300 && sum0<500)
        {
            disct = 0.95;
        }
        else if(sum0>=500&&sum0<1000)
        {
            disct = 0.9;
        }
        else if(sum0>=1000)
        {
            disct = 0.8;
        }
    }
    QDateTime ti=QDateTime::currentDateTime();
    QString tptp;
    std::string rea=ui->goodname->text().trimmed().toStdString();
    std::string buytype;
    if(x==0) buytype="散户";
    else buytype=_name;
    if(tmp->typ==0) tptp=QString::asprintf("卖出%s %s %s",tmp->number,rea.c_str(),buytype.c_str());
    else tptp=QString::asprintf("卖出%s %s %s",tmp->number,rea.c_str(),buytype.c_str());
    rea=tptp.toStdString();
    //strcat(rr.c_str(),rea.c_str());
    IAEP xp;
    xp = (IAEP)malloc(M);        //申请一段大小为M 的空间
    xp->iae=tmp->outprice*ui->sellcnt->value()*disct;
    //printf("请输入收支类型（-代表支出，+代表收入）：");
    //scanf("%c", &p->ch);
    xp->ch='+';
    //printf("请输入时间（年 月 日）：");
    //scanf("%d%d%d", &p->year, &p->month, &p->day);
    xp->year=ti.toString("yy").toInt();
    xp->month=ti.toString("MM").toInt();
    xp->day=ti.toString("dd").toInt();
    //printf("请输入收入来源或支出目的：");
    //gets(p->source_or_aim);
    strcpy(xp->source_or_aim,rea.c_str());
    //保存p到文件中
    FILE* fp;       //文件指针
    fp = fopen("admin123", "ab");    //以追加的方式打开文件
    if (fp == NULL)
    {
        //printf("cannot open file\n");
        QMessageBox::warning(this,"err","打开文件失败！");
        fclose(fp);//关闭文件
    }
    else if (fwrite(xp, M, 1, fp) != 1)    //将p所指向的1个大小为M的数据结构写入fp所指向的文件中
    {
        //printf("file write error\n");
        QMessageBox::warning(this,"err","文件写入失败！");
        fclose(fp);//关闭文件
    }
    else {
        fclose(fp);//关闭文件
    }
    if(x==0) return;

    //以下为会员入账
    xp = (IAEP)malloc(M);        //申请一段大小为M 的空间
    xp->iae=tmp->outprice*ui->sellcnt->value()*disct;
    xp->ch='-';
    xp->year=ti.toString("yy").toInt();
    xp->month=ti.toString("MM").toInt();
    xp->day=ti.toString("dd").toInt();
    QString tttt;
    tttt=QString::asprintf("购买%lf %s",ui->sellcnt->value(),rea.c_str());
    rea=tttt.toStdString();
    strcpy(xp->source_or_aim,rea.c_str());
    fp = fopen(_name.c_str(), "ab");    //以追加的方式打开文件
    if (fp == NULL)
    {
        //printf("cannot open file\n");
        QMessageBox::warning(this,"err","打开文件失败！");
        fclose(fp);//关闭文件
    }
    else if (fwrite(xp, M, 1, fp) != 1)    //将p所指向的1个大小为M的数据结构写入fp所指向的文件中
    {
        //printf("file write error\n");
        QMessageBox::warning(this,"err","文件写入失败！");
        fclose(fp);//关闭文件
    }
    else {
        fclose(fp);//关闭文件
    }
}

void ad_sell::on_pushButton_clicked()//散户买账
{
    buyer=0;
}

void ad_sell::on_sumbtn_clicked()//结算
{
    QStandardItem *aItem;
    aItem=new QStandardItem(QString::asprintf("总购买商品数"));
    aItem->setTextAlignment(Qt::AlignHCenter);
    themodel->setItem(num,0,aItem);
    aItem=new QStandardItem(QString::asprintf("总花费"));
    aItem->setTextAlignment(Qt::AlignHCenter);
    themodel->setItem(num,2,aItem);
    num++;
    aItem=new QStandardItem(QString::asprintf("%d",num-1));
    aItem->setTextAlignment(Qt::AlignHCenter);
    themodel->setItem(num,0,aItem);
    aItem=new QStandardItem(QString::asprintf("%.2lf",sum));
    aItem->setTextAlignment(Qt::AlignHCenter);
    themodel->setItem(num,2,aItem);
    num=0;          //初始化商品数量
    disct=1.00;     //初始化折扣力度
    sum=0;          //消费金额清零
    buyer=0;        //购买者重置为散户
    ui->buyername->setText("散户(非会员)");
}

void ad_sell::on_action_3_triggered()//会员充值
{
    hycz *cz=new hycz(this);
    cz->show();
}
